package com.abc.scholarship.service.impl;

import com.abc.scholarship.config.security.utils.MenuTree;
import com.abc.scholarship.domain.entity.Menu;
import com.abc.scholarship.domain.entity.Role;
import com.abc.scholarship.domain.entity.User;
import com.abc.scholarship.domain.vo.resp.MenuQueryVo;
import com.abc.scholarship.domain.vo.resp.RoleMenuVo;
import com.abc.scholarship.mapper.MenuMapper;
import com.abc.scholarship.mapper.RoleMapper;
import com.abc.scholarship.mapper.UserMapper;
import com.abc.scholarship.service.MenuService;
import com.abc.scholarship.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jzw
 * @since 2024-07-02
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private UserMapper userMapper;

    /**根据id查询权限列表
     *
     * @param userId
     * @return
     */

    public List<Menu> findMenuListByUserId(Long userId) {
        return baseMapper.findMenuListByUserId(userId);
    }

    /**查询菜单列表
     *
     * @param permissionQueryVo
     * @return
     */

    public List<Menu> findMenuList(MenuQueryVo permissionQueryVo) {
        //创建条件构造器对象    
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<Menu>();
        //排序    
        queryWrapper.orderByAsc("order_num");
        //调用查询菜单列表的方法    
        List<Menu> permissionList = baseMapper.selectList(queryWrapper);
        //生成菜单树    
        List<Menu> menuTree = MenuTree.makeMenuTree(permissionList, 0L);
        //返回数据    
        return menuTree;
    }

    /**查询上级菜单列表
     *
     * @return
     */

    public List<Menu> findParentMenuList() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<Menu>();
        //只查询type为目录和菜单的数据(type=0或type=1)    
        queryWrapper.in("type", Arrays.asList(0,1));
        //排序    
        queryWrapper.orderByAsc("order_num");
        //查询菜单数据    
        List<Menu> permissionList = baseMapper.selectList(queryWrapper);
        //构造顶级菜单信息，如果数据库中的菜单表没有数据，选择上级菜单时则显示顶级菜单    
        Menu permission = new Menu();
        permission.setId(0);
        permission.setParentId(-1L);
        permission.setLabel("顶级菜单");
        permissionList.add(permission);//将顶级菜单添加到集合    
        // 生成菜单数据    
        List<Menu> menuTree = MenuTree.makeMenuTree(permissionList, -1L);
        //返回数据    
        return menuTree;
    }

    /** 检查是否有子菜单
     *
     * @param id
     * @return
     */

    public boolean hasChildrenOfMenu(Long id) {
        //创建条件构造器对象    
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<Menu>();
        //查询父级ID    
        queryWrapper.eq("parent_id", id);
        //判断数量是否大于0，如果大于0则表示存在    
        if(baseMapper.selectCount(queryWrapper)>0){
            return true;
        }
        return false;
    }

    @Override
    public RoleMenuVo findMenuTree(Long userId, Long roleId) {
        User user = userMapper.selectById(userId);
        List<Menu> list = null;
        if(!ObjectUtils.isEmpty(user.getUName()) && user.getUName().equals("admin")){
            list = baseMapper.selectList(null);
        }else{
            list = baseMapper.findMenuListByUserId(userId);
        }
        // 组装成树数据
        List<Menu> permissionList = MenuTree.makeMenuTree(list,0L);

        // 查询要分配角色的原有权限
        List<Menu> rolePermissions = baseMapper.findMenuListByRoleId(roleId);

        // 找出该角色存在的数据
        List<Long> listIds = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(item -> {
                    Optional.ofNullable(rolePermissions).orElse(new ArrayList<>())
                            .stream()
                            .filter(Objects::nonNull)
                            .forEach(obj -> {
                                if(item.getId().equals(obj.getId())){
                                    listIds.add(obj.getId().longValue()); // 强制转为Long
                                    return;
                                }
                            });
                });
        // 创建
        RoleMenuVo vo = new RoleMenuVo();
        vo.setMenuList(permissionList);
        vo.setCheckList(listIds.toArray());
        return  vo;
    }

}
